<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Department extends Model
{
    use HasFactory;

    /**
     * 表名
     */
    protected $table = 'departments';

    /**
     * 可填充的字段
     */
    protected $fillable = [
        'code',
        'name',
        'parent_id',
        'level',
        'manager_id',
        'description',
        'status',
        'sort_order',
        'phone',
        'email',
        'address',
        'establishment_date',
        'budget',
        'current_budget',
        'notes',
    ];

    /**
     * 类型转换
     */
    protected $casts = [
        'establishment_date' => 'date',
        'budget' => 'decimal:2',
        'current_budget' => 'decimal:2',
    ];

    /**
     * 获取上级部门
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Department::class, 'parent_id');
    }

    /**
     * 获取子部门
     */
    public function children(): HasMany
    {
        return $this->hasMany(Department::class, 'parent_id');
    }

    /**
     * 获取部门经理
     */
    public function manager(): BelongsTo
    {
        return $this->belongsTo(User::class, 'manager_id');
    }

    /**
     * 获取部门员工
     */
    public function employees(): HasMany
    {
        return $this->hasMany(Employee::class, 'department_id');
    }

    /**
     * 获取部门岗位配置
     */
    public function departmentPositions(): HasMany
    {
        return $this->hasMany(DepartmentPosition::class);
    }

    /**
     * 获取部门报表
     */
    public function reports(): HasMany
    {
        return $this->hasMany(DepartmentReport::class);
    }

    /**
     * 获取考勤汇总
     */
    public function attendanceSummaries(): HasMany
    {
        return $this->hasMany(AttendanceSummary::class);
    }

    /**
     * 获取招聘预警
     */
    public function recruitmentWarnings(): HasMany
    {
        return $this->hasMany(RecruitmentWarning::class);
    }

    /**
     * 获取所有子部门（递归）
     */
    public function allChildren(): HasMany
    {
        return $this->children()->with('allChildren');
    }

    /**
     * 获取部门层级路径
     */
    public function getPathAttribute(): string
    {
        $path = [$this->name];
        $parent = $this->parent;

        while ($parent) {
            array_unshift($path, $parent->name);
            $parent = $parent->parent;
        }

        return implode(' > ', $path);
    }

    /**
     * 获取部门状态标签
     */
    protected function statusLabel(): Attribute
    {
        return Attribute::make(
            get: function () {
                return match ($this->status) {
                    'active' => '正常',
                    'inactive' => '停用',
                    'dissolved' => '撤销',
                    default => '未知',
                };
            }
        );
    }

    /**
     * 获取预算使用率
     */
    protected function budgetUsageRate(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!$this->budget || $this->budget == 0) {
                    return 0;
                }
                return round(($this->current_budget / $this->budget) * 100, 2);
            }
        );
    }

    /**
     * 获取员工数量
     */
    protected function employeeCount(): Attribute
    {
        return Attribute::make(
            get: function () {
                return $this->employees()->active()->count();
            }
        );
    }

    /**
     * 作用域：活跃部门
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 作用域：按层级筛选
     */
    public function scopeByLevel($query, int $level)
    {
        return $query->where('level', $level);
    }

    /**
     * 作用域：顶级部门
     */
    public function scopeRoot($query)
    {
        return $query->whereNull('parent_id');
    }

    /**
     * 作用域：子部门
     */
    public function scopeChildrenOf($query, int $parentId)
    {
        return $query->where('parent_id', $parentId);
    }

    /**
     * 作用域：按预算范围筛选
     */
    public function scopeByBudgetRange($query, float $min, float $max)
    {
        return $query->whereBetween('budget', [$min, $max]);
    }

    /**
     * 检查是否为叶子节点
     */
    public function isLeaf(): bool
    {
        return $this->children()->count() === 0;
    }

    /**
     * 获取所有上级部门ID
     */
    public function getParentIds(): array
    {
        $ids = [];
        $parent = $this->parent;

        while ($parent) {
            $ids[] = $parent->id;
            $parent = $parent->parent;
        }

        return array_reverse($ids);
    }

    /**
     * 获取所有子部门ID
     */
    public function getChildrenIds(): array
    {
        $ids = [];
        $this->collectChildrenIds($this, $ids);
        return $ids;
    }

    /**
     * 递归收集子部门ID
     */
    private function collectChildrenIds(Department $department, array &$ids): void
    {
        foreach ($department->children as $child) {
            $ids[] = $child->id;
            $this->collectChildrenIds($child, $ids);
        }
    }
}